package com.treeHole.treeHoleServer.service.impl;

import com.treeHole.treeHoleServer.service.EmailService;
import com.zaxxer.hikari.util.ClockSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    // 使用一个简单的缓存来存储验证码
    private Map<String, String> emailCodeCache = new HashMap<>();

    private String generateVerificationCode() {
        // 生成 6 位随机数字验证码
        return String.format("%06d", new Random().nextInt(999999));
    }

    @Override
    public void sendVerificationCode(String email) {
        // 生成验证码并存入缓存
        String code = generateVerificationCode();
        emailCodeCache.put(email, code);

        // 创建邮件内容
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(email);
        message.setSubject("同学你好!");
        message.setText("你的验证码为: " + code);

        // 发送邮件
        mailSender.send(message);
        log.info("已发送验证码到:{}",email);
    }

    @Override
    public boolean verifyCode(String email, String code) {
        // 从缓存中获取验证码并进行比对
        String cachedCode = emailCodeCache.get(email);
        Boolean success= Boolean.FALSE;
        if(cachedCode!=null&&cachedCode.equals(code)){
            emailCodeCache.remove(email);
            success = Boolean.TRUE;
        }
        return success;
    }
}